/**
 * Created by shenc on 2015/12/4.
 */

var tools = {};

//对consloe的扩展
//项目中禁用控制台输出的方法是，在页面配置中加上: var TOOLS_DEBUG = false;
tools.log = function () {
    if (typeof TOOLS_DEBUG !== 'undefined' && !TOOLS_DEBUG)return;
    if ('console' in window) {
        for (var i = 0, il = arguments.length; i < il; i++) {
            if (typeof arguments[i] === 'string') {
                console.log(decodeURIComponent(arguments[i]));
                continue;
            }
            try {
                console.log(arguments[i]);
            } catch (e) {
                console.log("console这个对象的时候出错了！");
            }
        }
    } else {
        alert(Array.prototype.slice.call(arguments, 0).join(' '));
    }
};

//模板替换
//默认匹配字符:"${xxx}";
tools.htmlTemplate = function (template, data, allowEmpty, chats) {
    var regExp;
    chats = chats || ['\\$\\{', '\\}'];
    regExp = [chats[0], '([_\\w]+[\\w\\d_]?)', chats[1]].join('');
    regExp = new RegExp(regExp, 'g');
    //${xxx}
    return template.replace(regExp,
        //该函数的第一个参数是匹配模式的字符串(例子：${name})。接下来的参数是与模式中的子表达式匹配的字符串(例子：name)，可以有 0 个或多个这样的参数。接下来的参数是一个整数，声明了匹配在 stringObject 中出现的位置。最后一个参数是 stringObject 本身。
        function (s, s1) {
            if (data[s1] != null && data[s1] != undefined) {
                return data[s1];
            } else {
                return allowEmpty ? '' : s;
            }
        });
};

/*日期处理工具*/
tools.date = {
    /**
     * 日期格式化
     * format 格式应为 "YYYY-MM-DD hh:mm:ss S q" 这样的组合
     * 可以传入 指定日期，如："2018/07/8 18:45:13"
     */
    format: function (format, time) {
        var now = time ? new Date(time) : new Date();
        var o = {
            "M+": now.getMonth() + 1,     //month
            "D+": now.getDate(),        //day
            "h+": now.getHours(),       //hour
            "m+": now.getMinutes(),     //minute
            "s+": now.getSeconds(),     //second
            "q+": Math.floor((now.getMonth() + 3) / 3), //quarter
            "S": now.getMilliseconds() //millisecond
        };

        if (/(Y+)/.test(format)) {
            format = format.replace(RegExp.$1, (now.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    },
    //获取年月日  可以传dates 往前+ 或 往后- 得到最终日期
    getDate: function (dates) {
        var dd = new Date();
        dd.setDate(dd.getDate() + dates);

        var y = dd.getFullYear();
        var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
        var d = dd.getDate() < 10 ? "0" + (dd.getDate()) : dd.getDate();
        return y + "-" + m + "-" + d;
    },
    //本周一与当前日期相差的天数  monday
    getMonday: function () {
        var d = new Date();
        //周
        var day = d.getDay();
        return (day != 0) ? day - 1 : 6; // 本周一与当前日期相差的天数  monday
    }
};

//产生随机数
tools.getRandomNum = function (Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return(Min + Math.round(Rand * Range));
};

//是否包含指定css属性
tools.hasAttr = function (attr) {
    return (attr in document.createElement("div").style);
};

//html5特性检测
tools.html5support = {
    canvas: function () {
        var hasCanvas = true;
        try {
            document.createElement('canvas').getContext('2d');
        } catch (e) {
            hasCanvas = false;
        }
        return hasCanvas
    }
};

//数组去重
tools.unique = function (arr) {
    var n = {}, r = []; //n为hash表，r为临时数组
    for (var i = 0; i < arr.length; i++) //遍历当前数组
    {
        if (!n[arr[i]]) //如果hash表中没有当前项
        {
            n[arr[i]] = true; //存入hash表
            r.push(arr[i]); //把当前数组的当前项push到临时数组里面
        }
    }
    return r;
};

//剩余字数统计
tools.textNum = function (textArea, numItem) {
    if (!textArea || !numItem || textArea.length == 0 || numItem.length == 0) {
        return;
    }
    var max = numItem.text(),
        curLength;
    textArea[0].setAttribute("maxlength", max);
    curLength = textArea.val().length;
    numItem.text(max - curLength);
    textArea.on('input propertychange', function () {
        numItem.text(max - $(this).val().length);
    });
};

//js动态插入css或者js文件
//tools.loadJs("css/base.js",callback,[["attr1","xx"],["attr2","yy"]])
tools.loadJs = function (filename, callback, attrArr) {
    var fileRef = document.createElement('script');         //创建标签
    fileRef.type = "text/javascript";   //定义属性type的值为text/javascript
    fileRef.src = filename;              //文件的地址
    if (attrArr) {
        var attrLen = attrArr.length;
        for (var i = 0; i < attrLen; i++) {
            fileRef.setAttribute(attrArr[i][0], attrArr[i][1]);
        }
    }
    if (callback && typeof callback == "function") {
        if (fileRef.readyState) {
            fileRef.onreadystatechange = function () {
                if (fileRef.readyState == "loaded" || fileRef.readyState == "complete") {
                    fileRef.onreadystatechange = null;
                    callback();
                    document.getElementsByTagName("head")[0].removeChild(this);
                }
            };
        }
        else {
            fileRef.onload = function () {
                callback();
                document.getElementsByTagName("head")[0].removeChild(this);
            };
        }
    }
    document.getElementsByTagName("head")[0].appendChild(fileRef);
    return this
};
tools.loadStyle = function (src, callFn, id) {
    var callBack = callFn ? callFn : function () {
    };
    //var linkId = id||"tempStyle";
    function styleOnload(node, callback) {
        // for IE6-9 and Opera
        if (node.attachEvent) {
            node.attachEvent('onload', callback);
            // NOTICE:
            // 1. "onload" will be fired in IE6-9 when the file is 404, but in
            // this situation, Opera does nothing, so fallback to timeout.
            // 2. "onerror" doesn't fire in any browsers!
        }
        // polling for Firefox, Chrome, Safari
        else {
            setTimeout(function () {
                poll(node, callback);
            }, 0); // for cache
        }
    }

    function poll(node, callback) {
        if (callback.isCalled) {
            return;
        }
        var isLoaded = false;
        if (/webkit/i.test(navigator.userAgent)) {//webkit
            if (node['sheet']) {
                isLoaded = true;
            }
        }
        // for Firefox
        else if (node['sheet']) {
            try {
                if (node['sheet'].cssRules) {
                    isLoaded = true;
                }
            } catch (ex) {
                // NS_ERROR_DOM_SECURITY_ERR
                if (ex.code === 1000) {
                    isLoaded = true;
                }
            }
        }
        if (isLoaded) {
            // give time to render.
            setTimeout(function () {
                callback();
            }, 1);
        }
        else {
            setTimeout(function () {
                poll(node, callback);
            }, 1);
        }
    }

    function loadCss(src, callFn, id) {
        var node = document.createElement("link");
        node.setAttribute("rel", "stylesheet");
        node.setAttribute("type", "text/css");
        node.setAttribute("href", src);
        if (id && document.getElementById(id)) {
            node.setAttribute("id", "tempStyle");
            document.body.appendChild(node);
            document.getElementById(id).href = src;
        } else {
            node.setAttribute("id", id);
            document.getElementsByTagName("head")[0].appendChild(node);
        }
        styleOnload(node, callFn);
        /*styleOnload(node,function(){
         alert("loaded");
         });*/
    }

    loadCss(src, callBack, id);
};

tools.url2Json = function (str) {
    var arguments = str ? str.split("&") : window.location.search.replace("?", "").split("&"),
        data = {};
    for (var i = 0; i < arguments.length; i++) {
        var tempArr = arguments[i].split("=");
        tempArr[0] && (data[tempArr[0]] = tempArr[1])
    }
    return data;
};

tools.reposition = function ($el, $box) {
    var xEnd,
        yEnd,
        runFun = function () {
            xEnd = $el.offset().left;
            yEnd = $el.offset().top + $el.outerHeight();
            $box.animate({"left": xEnd, "top": yEnd})
        };
    tools.timeOutRun($(window), "resize", runFun, 200);
};

//按钮时间倒计时
tools.buttonCountdown = function ($el, sNum, timeFormat, text,cb) {
    var t = 0,
        temp,
        defTxt = $el.text();
    var _text = text || "";
    var start = function (sNum) {
        temp = setInterval(function () {
            t = t + 1000;
            $el.text(showTime((sNum - t))[timeFormat] + _text);
            if ((sNum - t) == 0) {
                $el.prop("disabled", false).removeClass("disabled").text(defTxt);
                clearInterval(temp);

                if(typeof cb =='function'){
                    cb();
                }
            }
        }, 1000)
    };
    setTimeout(function () {
        $el.prop("disabled", true).addClass("disabled");
        sNum&&start(sNum)
    }, 0);
    this.clearTime = function () {
        clearInterval(temp);
    };
    function showTime(ms) {
        var d = Math.floor(ms / 1000 / 60 / 60 / 24),
            h = Math.floor(ms / 1000 / 60 / 60 % 24),
            m = Math.floor(ms / 1000 / 60 % 60),
            s = Math.floor(ms / 1000 % 60);
        return {
            d: d + "天",
            h: h + "小时",
            m: m + "分",
            s: s + "秒",
            "d:h:m:s": d + "天" + h + "小时" + m + "分" + s + "秒",
            "h:m:s": h + "小时" + m + "分" + s + "秒",
            "m:s": m + "分" + s + "秒"
        };
    }

    return this;
};

tools.goToY = function (y, time, callback) {
    var temp = 0;
    $("html,body").animate({scrollTop: y || 0}, time || 600, function () {
        if (!temp && callback) {
            temp = 1;
            callback();
        }
    });
    return false;
};

//时间差
tools.timeDiff = function (varName) {
    var start = window["diffTime-" + varName] || 0,
        ms = new Date().getTime();
    window["diffTime-" + varName] = ms;
    return ms - start;
};

//浏览器版本判断
//示例：tools.Browser().chrome 判断是不是chrome浏览器
//     tools.Browser().ver    获取浏览器版本号
tools.Browser = function () {
    var browserName = navigator.userAgent.toLowerCase();
    this.ver = (browserName.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1];
    this.msie = /msie/i.test(browserName) && !/opera/.test(browserName);
    this.firefox = /firefox/i.test(browserName);
    this.chrome = /chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName);
    this.opera = /opera/i.test(browserName);
    this.safari = /webkit/i.test(browserName) && !(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName));
    return this;
};

//产生浏览器样式前缀
tools.prefix = function (attr, val) {
    var prefix = ["-o-", "-webkit-", "-moz-", "-ms-"],
        obj = {};
    for (var i = 0; i < prefix.length; i++) {
        obj[prefix[i] + attr] = val;
    }
    return obj;
};

//前端测试用方法，上线后不影响正常使用
//url: ['url',{Flag:1,Content:''}]   ||   ['url','demo data url']  ||  'url'
tools.post = function (url, data, cb, type) {
    if (CONFIG.isDebugger) {
        if (typeof url === 'object') {
            if (typeof url[1] === 'string') {
                $.post(url[1], data, cb, type);
            } else {
                cb(url[1])
            }
        } else {
            $.post(url[1], data, cb, type);
        }
    } else {
        if (typeof url === 'string') {
            $.post(url, data, cb, type);
        } else {
            $.post(url[0], data, cb, type);
        }
    }
};

//过滤非法字符
tools.escapeRegExChars= function (value) {
    return value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

//cookies操作
/*
 * setCookie("name","hayden","s20");
 * s20是代表20秒
 * h是指小时，如12小时则是：h12
 * d是天数，30天则：d30
 */
function setCookie(name, value, time, path, domain) {
    var _expires, _path, _domain;
    if (time) {
        var strSec = getSec(time) - 0,
            exp = new Date();
        exp.setTime(exp.getTime() + strSec);
        _expires = ";expires=" + exp.toUTCString()
    } else {
        _expires = "";
    }
    _path = path ? ";path=" + path : ";path=/";
    _domain = domain ? ";domain=" + domain : "";
    document.cookie = name + "=" + encodeURI(value) + _expires + _path + _domain;
}

function getSec(str) {
    var str1 = str.substring(1, str.length) - 0;
    var str2 = str.substring(0, 1);
    var obj = {
        "s": str1 * 1000,
        "h": str1 * 60 * 60 * 1000,
        "d": str1 * 24 * 60 * 60 * 1000
    };
    return obj[str2];
}

//读取cookies
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))
        return decodeURI(arr[2]);
    else
        return null;
}

